package com.chatdating.aspect;


import com.chatdating.annotate.IsLogin;
import com.chatdating.entity.vo.LoginInVo;
import com.chatdating.exception.BusinessException;
import com.chatdating.redis.RedisComponet;
import com.chatdating.utils.EmptyUtil;
import com.chatdating.utils.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component()
@Aspect
public class IsLoginSucess {

    @Resource
    private RedisComponet redisComponet;

    private static Logger logger = LoggerFactory.getLogger(IsLoginSucess.class);

    @Before("@annotation(com.chatdating.annotate.IsLogin)")  //切点 带有这个注解的会进行前置校验
    public void interceptorDo(JoinPoint point) throws Exception {

        // 获取当前执行方法的签名
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        // 获取到这个注解
        IsLogin interceptor = method.getAnnotation(IsLogin.class);
        if (null == interceptor) {  // (可忽略 不带注解不会进入这个方法)
            return;
        }
        /**
         * 校验登录
         */
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();  // 获取请求对象
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7); // 去除 "Bearer " 前缀
            if(EmptyUtil.isEmpty(token)){
                throw new BusinessException(404,"未登录");
            }else{
                LoginInVo tokenUserInfoDto = redisComponet.getTokenUserInfoDto(token);
                if(EmptyUtil.isEmpty(tokenUserInfoDto)){
                    throw new BusinessException(404,"未登录");
                }
            }
        }
    }
}


